package com.sensePlusVR.net;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;

import android.content.Context;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.main.R;
import com.sensePlusVR.utils.AndroidDeviceUtil;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.ConstantURL;
import com.sensePlusVR.utils.DeviceType;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.NetworkUtils;
import com.sensePlusVR.utils.SecureSocketFactory;
import com.sensePlusVR.utils.VersionUtil;
/**
 * 
 * @author: Loren
 * @create: 2016-6-14下午1:19:18
 * @desc: 访问网络封装
 *
 */
@SuppressWarnings({"deprecation"})
public class RequestUtils {
	
	private static final String TAG = RequestUtils.class.getSimpleName();
	
    // The certificate's alias.
    private static final String STORE_ALIAS = "aws-elb";

    // The certificate's password.
    private static final String STORE_PASS = "linknow123";
   
	public static AsyncHttpClient client = new AsyncHttpClient();
	//由于单例模式，所以区分携带Token和没有携带token对象
	public static AsyncHttpClient clientToken = new AsyncHttpClient();
	
	public static AsyncHttpClient clientBuried = new AsyncHttpClient();
	
	
	static {
        setTiemout();
        addCommonHeader();
        // Instruct the library to retry connection when this exception is raised.
        AsyncHttpClient.allowRetryExceptionClass(javax.net.ssl.SSLException.class);
    }
	
	private static void setTiemout(){
		//setting connection timed out
        client.setTimeout(10*1000); // 设置链接超时，如果不设置，默认为10s
        clientToken.setTimeout(10*1000);
        clientBuried.setTimeout(10*1000);
	}
	
	private static void addCommonHeader(){
		client.addHeader("user-agent", Constant.VALUE_USER_AGENT);
		clientToken.addHeader("user-agent", Constant.VALUE_USER_AGENT);
		clientBuried.addHeader("user-agent", Constant.VALUE_USER_AGENT);
		
	}
	
	

	//Get请求
	public static void clientGet(Context context,String url, NetCallBack cb) {
		setEncrytion(context);
		client.get(context, url, cb);
	}
	
	public static void clientGet(Context context,String url,RequestParams params, NetCallBack cb) {
		setEncrytion(context);
		client.get(context, url, params, cb);
	}
	
	public static void clientGet(Context context,String url,Header[] headers,RequestParams params, NetCallBack cb) {
		setEncrytion(context);
		client.get(context, url, headers, params, cb);
	}

	
	///Post请求
	public static void clientPost(Context context,String url,
			NetCallBack cb) {
		setEncrytion(context);
		client.post(url, cb);
	}
	
	public static void clientPost(Context context,String url, RequestParams params,
			NetCallBack cb) {
		setEncrytion(context);
		client.post(context, url, params, cb);
	}
	
	public static void clientPost(Context context,String url,HttpEntity entity,String contentType,
			NetCallBack cb) {
		setEncrytion(context);
		client.post(context, url, entity, contentType, cb);
	}
	
	public static void clientPost(Context context,String url,HttpEntity entity,
			NetCallBack cb) {
		setEncrytion(context);
		client.post(context, url, entity, null, cb);
	}
	
	public static void clientPost(Context context,String url,RequestParams params,String contentType,
			NetCallBack cb){
		setEncrytion(context);
		client.post(context, url, null, params, contentType, cb);
	}
	
	public static void clientPost(Context context,String url,Header[] deaders,HttpEntity entity,String contentType,
			NetCallBack cb) {
		setEncrytion(context);
		client.post(context, url, deaders, entity, contentType, cb);
	}
	
	public static void clientPost(Context context,String url,Header[] headers,RequestParams params,String contentType,
			NetCallBack cb) {
		setEncrytion(context);
		client.post(context, url, headers, params, contentType, cb);
	}
	
	//PUT请求
	public static void clientPut(Context context,String url,NetCallBack cb){
		setEncrytion(context);
		client.put(url, cb);
	}
	
	public static void clientPut(Context context,String url,RequestParams params,NetCallBack cb){
		setEncrytion(context);
		client.put(context,url, params, cb);
	}
	
	public static void clientPut(Context context,String url,HttpEntity entity,String contentType,NetCallBack cb){
		setEncrytion(context);
		client.put(context, url, entity, contentType, cb);
	}
	
	public static void clientPut(Context context,String url,Header[] deaders,HttpEntity entity,String contentType,NetCallBack cb){
		setEncrytion(context);
		client.put(context, url, deaders, entity, contentType, cb);
	}
	
	/*************************************************************带token的asynchttpclient对象方法*********************************************************************/
	
	//Get请求
	public static void clientTokenGet(Context context,String url, NetCallBack cb) {
		setEncrytion(context);
		clientToken.get(context, url, cb);
	}
	
	public static void clientTokenGet(Context context,String url,RequestParams params, NetCallBack cb) {
		setEncrytion(context);
		clientToken.get(context, url, params, cb);
	}
	
	public static void clientTokenGet(Context context,String url,Header[] headers,RequestParams params, NetCallBack cb) {
		setEncrytion(context);
		clientToken.get(context, url, headers, params, cb);
	}

	
	///Post请求
	public static void clientTokenPost(Context context,String url,
			NetCallBack cb) {
		setEncrytion(context);
		clientToken.post(url, cb);
	}
	
	public static void clientTokenPost(Context context,String url, RequestParams params,
			NetCallBack cb) {
		setEncrytion(context);
		clientToken.post(context, url, params, cb);
	}
	
	public static void clientTokenPost(Context context,String url,HttpEntity entity,String contentType,
			NetCallBack cb) {
		setEncrytion(context);
		clientToken.post(context, url, entity, contentType, cb);
	}
	
	public static void clientTokenPost(Context context,String url,HttpEntity entity,
			NetCallBack cb) {
		setEncrytion(context);
		clientToken.post(context, url, entity, null, cb);
	}
	
	public static void clientTokenPost(Context context,String url,RequestParams params,String contentType,
			NetCallBack cb){
		setEncrytion(context);
		clientToken.post(context, url, null, params, contentType, cb);
	}
	
	public static void clientTokenPost(Context context,String url,Header[] deaders,HttpEntity entity,String contentType,
			NetCallBack cb) {
		setEncrytion(context);
		clientToken.post(context, url, deaders, entity, contentType, cb);
	}
	
	public static void clientTokenPost(Context context,String url,Header[] headers,RequestParams params,String contentType,
			NetCallBack cb) {
		setEncrytion(context);
		clientToken.post(context, url, headers, params, contentType, cb);
	}
	
	//PUT请求
	public static void clientTokenPut(Context context,String url,NetCallBack cb){
		setEncrytion(context);
		clientToken.put(url, cb);
	}
	
	public static void clientTokenPut(Context context,String url,RequestParams params,NetCallBack cb){
		setEncrytion(context);
		clientToken.put(context,url, params, cb);
	}
	
	public static void clientTokenPut(Context context,String url,HttpEntity entity,String contentType,NetCallBack cb){
		setEncrytion(context);
		clientToken.put(context, url, entity, contentType, cb);
	}
	
	public static void clientTokenPut(Context context,String url,Header[] deaders,HttpEntity entity,String contentType,NetCallBack cb){
		setEncrytion(context);
		clientToken.put(context, url, deaders, entity, contentType, cb);
	}
	
	/*************************************************************Buried的asynchttpclient对象方法*********************************************************************/
	
	public static void clientBuriedPost(Context context,String url,HttpEntity entity,String contentType,
			NetCallBack cb) {
		setEncrytion(context);
		clientBuried.post(context, url, entity, contentType, cb);
	}
	
	
	/**
	 * @param context
	 * 设置加密参数
	 */
	private static void setEncrytion(Context context) {
		try {
              InputStream is = null;
              try {
                  // Configure the library to use a custom 'bks' file to perform
                  // SSL negotiation.
                  KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
                  is = context.getResources().openRawResource(R.raw.store);
                  store.load(is, STORE_PASS.toCharArray());
                  client.setSSLSocketFactory(new SecureSocketFactory(store, STORE_ALIAS));
              } catch (IOException e) {
                  MyLog.e(TAG, "Unable to initialize key store", e);
                  throw new KeyStoreException(e);

              } catch (CertificateException e) {
                  throw new KeyStoreException(e);
              } catch (NoSuchAlgorithmException e) {
                  throw new KeyStoreException(e);
              } catch (KeyManagementException e) {
                  throw new KeyStoreException(e);
              } catch (UnrecoverableKeyException e) {
                  throw new KeyStoreException(e);
              } finally {
                  AsyncHttpClient.silentCloseInputStream(is);
              }
          } catch (KeyStoreException e) {
              MyLog.e(TAG, "Unable to initialize key store", e);
         }
	}
	
	
	public static void setBurieHeaders(Context context){
		//String contentType = Constant.STR_APPLICATION_JSON;
		String token = MySharedPreferences.getString2(VRApplication.getAppContext(), MySharedPreferences.NAME_NOT_CLEAR,Constant.LOGIN_SUCCESS_TOKEN);
		String client_type  = Constant.VALUE_CLIENT_TYPE;
		String client_id = ConstantURL.VALUE_CLIENT_ID;
		String channel_id = ConstantURL.VALUE_CHANNEL_ID;
		String device_no =  AndroidDeviceUtil.getCustomUniqueIdentifier(context);//12~32位
		String os_type = DeviceType.ANDROID.getDevice();
		String os_version = AndroidDeviceUtil.getBuildVersion();
		String hard_ware = AndroidDeviceUtil.getPhoneBrand() + AndroidDeviceUtil.getPhoneModel();
		String version = VersionUtil.getVersionNameOnlyNum(context);
		String mac = AndroidDeviceUtil.getLocalMacAddress(context);
		String network_mode = NetworkUtils.getNetConnectStateStr(context);
		//String hedno = AndroidDeviceUtil.getDeviceSIMOperator(context);
		
		//在请求出已经传递过Content-Type
		//RequestUtils.clientBuried.addHeader("Content-Type", contentType);
		RequestUtils.clientBuried.addHeader("x-auth-token", token);
		RequestUtils.clientBuried.addHeader("Client-Type", client_type);
		RequestUtils.clientBuried.addHeader("Client-ID", client_id);
		RequestUtils.clientBuried.addHeader("Channel-ID", channel_id);
		RequestUtils.clientBuried.addHeader("Device-No", device_no == null?"":device_no);
		RequestUtils.clientBuried.addHeader("OS-Type", os_type);
		RequestUtils.clientBuried.addHeader("OS-Version", os_version == null?"":os_version);
		RequestUtils.clientBuried.addHeader("Hard-Ware", hard_ware == null?"":hard_ware);
		RequestUtils.clientBuried.addHeader("Version", version);
		RequestUtils.clientBuried.addHeader("Mac", mac == null?"":mac);
		RequestUtils.clientBuried.addHeader("Network-Mode", network_mode);
		//RequestUtils.clientBuried.addHeader("Hedno", hedno);
		
	}
	
}
